/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.feature.payment.core.wxpay.util;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import com.thoughtworks.xstream.io.xml.XmlFriendlyNameCoder;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ConnectionPoolTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yhao.infra.feature.payment.core.wxpay.config.WinXinConfig;

import java.net.SocketTimeoutException;

/**
 * User: rizenguo
 * Date: 2014/10/23
 * Time: 14:59
 */
public class HttpsReqWithCredentials {
    private final static Logger logger = LoggerFactory.getLogger(HttpsReqWithCredentials.class);

    public static String sslRequestPost(String url, Object xmlObj, WinXinConfig winXinConfig) throws Exception {
        CloseableHttpClient httpclient = winXinConfig.getHttpclient();
        String result = null;
        HttpPost httpPost = new HttpPost(url);

        //解决XStream对出现双下划线的bug
        XStream xStreamForRequestPostData = new XStream(new DomDriver("UTF-8", new XmlFriendlyNameCoder("-_", "_")));

        //将要提交给API的数据对象转换成XML格式数据Post给API
        String postDataXML = xStreamForRequestPostData.toXML(xmlObj);
        logger.info("[pay:weixin][post]");
        logger.info(postDataXML);

        //得指明使用UTF-8编码，否则到API服务器XML的中文不能被成功识别
        StringEntity postEntity = new StringEntity(postDataXML, "UTF-8");
        httpPost.addHeader("Content-Type", "text/xml");
        httpPost.setEntity(postEntity);

        //设置请求器的配置
        httpPost.setConfig(winXinConfig.getRequestConfig());

        try {
            //httpost.addHeader("Connection", "keep-alive");// 设置一些heander等
            CloseableHttpResponse response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            // 返回结果
            result = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (ConnectionPoolTimeoutException e) {
            logger.error("[pay:weixin]" + "http get throw ConnectionPoolTimeoutException(wait time out)");
        } catch (ConnectTimeoutException e) {
            logger.error("[pay:weixin]" + "http get throw ConnectTimeoutException");
        } catch (SocketTimeoutException e) {
            logger.error("[pay:weixin]" + "http get throw SocketTimeoutException");
        } catch (Exception e) {
            logger.error("[pay:weixin]" + "http get throw Exception");
        } finally {
            httpPost.abort();
        }
        return result;
    }
}
